<template>
  <div class="dialog">
    <el-dialog :title="'添加投塘'" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="关联批次选择：" prop="batchObj" class="w50p">
          <el-select  v-model="formData.batchObj" value-key="productionBatchId" filterable clearable @change="batchChange">
            <el-option v-for="(item, index) in batchList" :key="index" :label="`${item.mnecode}_${item.varietyName}`" :value="{
              productionBatchId: item.productionBatchId,
              fishVarietyId: item.fishVarietyId,
            }" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用称重记录：" prop="weightToPondDetail" class="w50p">
          <el-select  @change="isChooseWeightRecord = true" v-model="formData.weightToPondDetail" filterable clearable>
            <el-option label="是" :value="true" :disabled="!weightRecordList.length" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <transition name="fade">
          <el-form-item v-show="formData.weightToPondDetail === true" label="称重记录：" prop="weightRecordId" class="w100p">
            <el-button type="info" round style="height: 36px" @click="selectWeightRecord">点击选择称重记录</el-button>
            <div v-if="!isChooseWeightRecord" class="hang-content" style="color: red; text-align: left; padding: 0 15px">
              请选择称重记录
            </div>
            <div class="hang-content">
              <div v-for="(key, index) in BOList" :key="index + 'deviceCode'" class="hang-content-one">
                <el-input v-model="key.specName" disabled>
                  <template slot="prepend">规格</template>
                  <template slot="append">斤/尾</template>
                </el-input>
                <el-input v-model="key.num" disabled>
                  <template slot="prepend">数量</template>
                  <template slot="append">尾</template>
                </el-input>
                <el-input v-model="key.weight" disabled>
                  <template slot="prepend">重量</template>
                  <template slot="append">斤</template>
                </el-input>
              </div>
            </div>
          </el-form-item>
        </transition>
        <transition name="fade">
          <el-form-item v-show="formData.weightToPondDetail === false" label="投入规格：" prop="specificationId" class="w50p">
            <el-select  v-model="inputPondDetail.specificationId" filterable clearable>
              <el-option v-for="(item, index) in specificationList" :key="index" :label="item.specificationName"
                :value="item.specificationId" />
            </el-select> </el-form-item>
        </transition>
        <transition name="fade">
          <el-form-item v-show="formData.weightToPondDetail === false" label="入鱼数量：" class="w50p" prop="inputNum">
            <el-input v-model="inputPondDetail.inputNum" clearable placeholder="请输入入鱼条数">
              <template slot="append">尾</template>
            </el-input>
          </el-form-item>
        </transition>
        <transition name="fade">
          <el-form-item v-show="formData.weightToPondDetail === false" label="入鱼重量：" class="w50p" prop="inputWeight">
            <el-input v-model="inputPondDetail.inputWeight" clearable placeholder="请输入投塘重量">
              <template slot="append">斤</template>
            </el-input>
          </el-form-item>
        </transition>
        <transition name="fade">
          <el-form-item v-show="isShowFormItem" label="投入鱼塘：" prop="fishPondId" class="w50p">
            <el-select  v-model="formData.fishPondId" filterable clearable placeholder="请选择投入鱼塘" :disabled="true">
              <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </el-form-item>
        </transition>
        <el-form-item label="投塘人：" class="w50p" prop="staffName">
          <el-select  v-model="formData.staffId" filterable clearable placeholder="非必填,默认当前登陆"
            @change="staffchange">
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="投塘日期：" class="w50p" prop="inputDate">
          <el-date-picker v-model="formData.inputDate" :picker-options="pickerOptions" type="datetime" placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="称重选择" :visible.sync="showWeightRecord" width="54%" top="0" :close-on-click-modal="false"
      @close="showWeightRecord = false">
      <el-table ref="rightTableData" :data="weightRecordList" highlight-current-row border stripe :row-key="(row) => {
        return row.weightRecordId;
      }
        " @selection-change="handleSelectionChange" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="(row) => {
          return !row.selectable;
        }
          " />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="batchName" label="批次编号" />
        <el-table-column prop="specName" label="规格（斤/尾）" />
        <el-table-column prop="num" label="数量（尾）" />
        <el-table-column prop="weight" label="重量（斤）" />
        <el-table-column prop="weightStaffName" label="称重人" />
        <el-table-column prop="weightDate" label="称重日期" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" style="color: #3699fb; text-decoration: underline"
              @click.native.prevent="toggleSelection(scope.$index, scope.row)">选择</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <div style="color: #000">暂无数据</div>
        </template>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="showWeightRecord = false">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="saveSelect">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import InputPondApi from "@/api/inputPond";
import WeightRecordApi from "@/api/inputPond/weight-record";
import SpecificationApi from "@/api/basic-info-manage/specification";
import BatchMangeApi from "@/api/batch-mange";
import StaffApi from "@/api/basic-info-manage/staff";
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: "",
  mixins: [dialogMixin],
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: "",
    },
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
    fishPondList: {
      type: [Array],
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      formData: {},
      batchObj: {},
      specificationList: [],
      weightRecordList: [],
      batchList: [],
      staffList: [],
      checkedIdList: [],
      BOList: [],
      inputPondDetail: {
        inputWeight: "",
        inputNum: "",
        specificationId: "",
      },
      rules: {
        batchObj: [
          {
            required: true,
            message: "请选择关联批次",
            trigger: ["change", "blur"],
          },
        ],
        fishVarietyId: [
          {
            required: true,
            message: "请选择投入品种",
            trigger: ["change", "blur"],
          },
        ],
        weightToPondDetail: [
          { required: true, message: "请选择是否称重", trigger: "blur" },
        ],
        fishPondId: [
          {
            required: true,
            message: "请选择投入鱼塘",
            trigger: ["change", "blur"],
          },
        ],
        staffId: [
          {
            required: true,
            message: "请选择投塘人",
            trigger: ["change", "blur"],
          },
        ],
        inputDate: [
          {
            required: true,
            message: "请选择投塘时间",
            trigger: ["change", "blur"],
          },
        ],
      },
      showDialog: this.show,
      showWeightRecord: false,
      isShowFormItem: true,
      isChooseWeightRecord: true,
      buildDateTime: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
    };
  },

  watch: {
    show(v) {
      maxTime = null
      this.showDialog = v;
      if (!v) {
        this.$refs["ruleForm"].resetFields();
        this.isChooseWeightRecord = false;
        console.log("重置表单验证");
      }
    },
    nowChanceStau(v) {
      if (v === "add") {
        this.inputPondDetail = {
          inputWeight: "",
          inputNum: "",
          specificationId: "",
        }
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
          inputDate: this.getNowTime(),
          fishPondId: this.editObject.fishPondId,
        };
        BatchMangeApi.productionBatchList({
          pondId: this.editObject.fishPondId,
        }).then((res) => {
          this.batchList = res.data;
        });
      }
      if (v === "edit") {
        this.formData = this.editObject;
        setTimeout(() => {
          this.batchChange(this.formData.productionBatchId)
        }, 1000);
      }
    },
  },
  created() {
    // this.queryFishVariety()
    // this.queryBatch()
    this.queryStaff();
    maxTime = null
  },
  mounted() { },
  methods: {
    changeTime(time) {
      let buildDateTime = new Date(this.buildDateTime).getTime(new Date(this.buildDateTime))
      let newtime = new Date(time).getTime(new Date(time))
      if (buildDateTime > newtime) {
        this.formData.inputDate = this.buildDateTime
        this.$message.info('投塘时间不得小于批次创建时间' + this.buildDateTime + '！')
      }
    },
    checkInt(rule, value, callback) {
      if (value) {
        if (Number(value) && value > 0) {
          callback();
        } else {
          return callback(new Error("请输入大于0的参数"));
        }
      }
    },
    staffchange(id) {
      this.staffList.forEach(item => {
        if (item.staffId == id) {
          this.formData.staffName = item.staffName
        }
      })
      console.log(this.formData)
    },
    // 查询未完成批次
    queryBatch() {
      BatchMangeApi.queryByCondition({ status: "UN_COMPLETE" }).then((res) => {
        if (res.success) {
          this.batchList = res.data;
        }
      });
    },
    async batchChange(e) {
      maxTime = ''
      this.formData.inputDate = new Date()
      this.$set(this.formData, "weightToPondDetail", "");
      this.querySpecification(e);
      await this.queryWeightRecord(e);
      this.batchList.find(item => {
        if (item.productionBatchId === e.productionBatchId) {
          this.buildDateTime = item.buildDateTime
          maxTime = new Date(item.buildDateTime)
          // this.formData.inputDate = this.formatDateTimeMHS(maxTime)
        }
      })
    },
    // 查询批次相关称重记录
    async queryWeightRecord(item) {
      if (!item.productionBatchId) return;
      const res = await WeightRecordApi.queryListByBatchId({
        productionBatchId: item.productionBatchId,
      });
      this.weightRecordList = res.data;
      this.formData.weightToPondDetail = res.data.length > 0 ? true : false;
      this.isChooseWeightRecord = true;
    },
    // 查询品种的规格
    querySpecification(item) {
      this.formData.productionBatchId = item.productionBatchId;
      let params = {
        fishVarietyId: item.fishVarietyId,
      };
      SpecificationApi.queryByCondition(params).then((res) => {
        if (res.success) {
          this.specificationList = res.data;
        }
      });
    },
    // 查询可选员工(投塘人)
    queryStaff() {
      StaffApi.queryByCondition().then((res) => {
        this.staffList = res.data;
      });
    },
    chooseWeightRecord() {
      this.isChooseWeightRecord =
        this.BOList.length == 0 && this.formData.weightToPondDetail
          ? false
          : true;
      console.log(this.isChooseWeightRecord);
    },
    save(formData) {
      console.log(this.inputPondDetail)
      this.chooseWeightRecord();
      this.$refs[formData].validate((valid) => {
        if (valid && this.isChooseWeightRecord) {
          if (!this.inputPondDetail["specificationId"] && !this.formData.weightToPondDetail) {
            this.$message.error('请选择规格')
            return false
          }
          if ((Number(this.inputPondDetail['inputNum']) <= 0 || Number(this.inputPondDetail['inputNum']) % 1 !== 0) && !this.formData.weightToPondDetail) {
            this.$message.error('入鱼数需大于0的数')
            return false
          }
          if ((Number(this.inputPondDetail["inputWeight"]) <= 0) && !this.formData.weightToPondDetail) {
            this.$message.error('入鱼重量需大于0')
            return false
          }
          if (this.nowChanceStau === "edit") {
            InputPondApi.edit(this.formData).then((res) => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.inputPondDetailList = [];
            if (this.inputPondDetail) {
              this.formData.inputPondDetailList.push(this.inputPondDetail);
            }
            this.formData.inputDate = this.formatDateTimeMHS(this.formData.inputDate)
            InputPondApi.add(this.formData).then((res) => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    selectWeightRecord() {
      this.showWeightRecord = true;
      this.$nextTick(function () {
        // 避免clearSelection方法报错
        this.$refs.rightTableData.clearSelection();
      });
    },
    saveSelect() {
      this.$set(this.formData, "weightRecordIdList", this.checkedIdList);
      this.chooseWeightRecord();
      this.showWeightRecord = false;
    },
    selectAll(list) {
      let notvalue = true;
      list.forEach((item) => {
        if (!item.weightRecordId) {
          notvalue = false;
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    toggleSelection(index, rows) {
      this.$refs.rightTableData.toggleRowSelection(rows);
    },
    handleSelectionChange(list) {
      this.BOList = list;
      this.checkedIdList = [];
      let emptyList = [];
      this.checkedIdList = list.map((item) => {
        if (item.weightRecordId) {
          return item.weightRecordId;
        } else {
          emptyList.push(item);
          return "";
        }
      });
    },
    close() {
      this.BOList = [];
      this.$emit("closeDialog");
    },
    cancel() {
      this.BOList = [];
      this.$emit("cancelDialog");
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table {
  position: relative;
  width: auto;
}

.hang-content {
  width: 100%;

  .hang-content-one {
    width: 100%;
    display: flex;
  }
}

@keyframes axisX {
  from {
    transform: translateX(-100%);
  }

  to {
    transform: translateX(0px);
  }
}

/* 2. 过渡类名 */
/* 开始 */
.fade-enter-active {
  animation: axisX 1s;
}

/* 结束 */
.fade-leave-active {
  animation: axisX 1s reverse;
}
</style>
